package com.cn.wang.pool;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisService {
	private static final Logger logger = Logger.getLogger(RedisService.class);

	private JedisPool pool = null;

	private static final RedisService INSTANCE = new RedisService();

	public static RedisService getInstance() {
		return INSTANCE;
	}
	private static final String host = "127.0.0.1";
	private static final int port = 6397;
	
	public void init() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(50);
		config.setMinIdle(5);
		config.setMaxIdle(10);
		config.setMaxWaitMillis(5000);
		config.setTestOnBorrow(true);
		pool = new JedisPool(config, host, port);

	}

	public String get(String key) {
		String value = null;
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			value = jedis.get(key);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (jedis != null)
				pool.returnResource(jedis);
		}
		return value;
	}

	public void set(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			jedis.set(key, value);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (jedis != null)
				pool.returnResource(jedis);
		}
	}
	
	public void delete(String key) {
		Jedis jedis = null;
		try {
			jedis = pool.getResource();
			jedis.del(key);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (jedis != null)
				pool.returnResource(jedis);
		}
	}
}
